// components/cart/Cart.js
import {
  times,
  plus
} from '../../libs/np'
Component({
  lifetimes: {
    ready () {
      this.cartAction = this.selectComponent('#cart-action')
    }
  },
  /**
   * 组件的属性列表
   */
  properties: {
    items: {
      type: Array,
      value: []
    }
  },
  pageLifetimes: {
    show() {
      this.updateCart()
    }
  },

  /**
   * 组件的初始数据
   */
  data: {
    count: 0,
    checkedCount: 0,
    canPay: false,
    checkAll: false,
    items: [],
    price: 0,
    originPrice: 0
  },

  observers: {
    items(val) {
      let checked = val.filter(it => it.checked)
      this.setData({
        // 至少一个被选中
        canPay: checked.length > 0,
        checkedCount: checked.reduce((prev, cur) => (prev + cur.num || 0), 0)
      })
    }
  },

  /**
   * 组件的方法列表
   */
  methods: {
    /**
     * 获取购物车
     * @private
     */
    getCart() {
      return wx.getStorageSync('cart') || []
    },

    /**
     * 加入购物车
     * 
     * @param {*} item 
     */
    addToCart(item) {
      let cart = this.getCart()
      let index = cart.findIndex(it => it.id === item.id)
      if (index === -1) {
        item.num = 1
        item.checked = true
        cart.push(item)
      } else {
        cart[index].num++
      }

      wx.setStorageSync('cart', cart)

      this.updateCart()

      this.cartAction.ani()
    },

    /**
     * 从购物车中移除
     * @param {*} item 
     */
    removeFormCart(item) {
      let cart = this.getCart()
      let newCart = cart.filter(it => it.id !== item.id)

      wx.setStorageSync('cart', newCart)

      this.updateCart()
    },

    /**
     * 确认清空购物车
     */
    handleClean() {
      wx.setStorageSync('cart', [])
      this.updateCart()
    },

    /**
     * 购物车中某项数据递增
     * 
     * @param {*} ev 
     */
    handleIncrement(ev) {
      const item = ev.detail
      this.addToCart(item)
    },

    /**
     * 购物车中某项数据递减
     * 
     * @param {*} ev 
     */
    handleDecrement(ev) {
      let index
      let target
      let that = this
      let cart = this.getCart()
      const item = ev.detail

      index = cart.findIndex(it => it.id === item.id)
      if (index > -1) {
        target = cart[index]
        if (target.num === 1) {
          wx.showModal({
            title: '温馨提示',
            content: '你确认删除此商品吗？',
            success: function (res) {
              if (res.confirm) {
                that.removeFormCart(target)
              }
            }
          })
        } else {
          target.num--
          cart[index] = target
          wx.setStorageSync('cart', cart)

          this.updateCart()
        }
      }
    },

    /**
     * 切换某项选中
     * @param {*} ev 
     */
    handleChecked(ev) {
      let {
        checked,
        item
      } = ev.detail
      let cart = this.getCart()
      let target = cart.find(it => it.id === item.id)
      if (target) {
        target.checked = checked
        wx.setStorageSync('cart', cart)

        this.updateCart()
      }
    },

    /**
     * 切换全选
     */
    handleCheckAll(ev) {
      let checkAll = ev.detail
      let cart = this.getCart()
      cart.forEach(it => it.checked = checkAll)
      wx.setStorageSync('cart', cart)

      this.updateCart()
    },

    updateCart() {
      let cart = this.getCart()
      let filteredCart = cart.filter(it => it.checked)
      // 商品总数
      let count = cart.reduce((prev, cur) => {
        return prev + (cur.num || 0)
      }, 0)
      // 是否全选中
      let checkAll = filteredCart.length > 0 && filteredCart.length === cart.length
      let price = 0
      let originPrice = 0
      filteredCart.forEach((it) => {
        price = plus(price, times(it.price, it.num))
        originPrice = plus(originPrice, times(it.originPrice, it.num))
      })
      this.setData({
        count,
        items: cart,
        checkAll,
        price,
        originPrice
      })
    },

    handlePay () {
      this.triggerEvent('pay')
    }
  }
})